from boto_web.appserver.handlers.db import DBHandler
from boto_web.resources.user import User
from boto.sdb.db.key import Key

from boto_web.exceptions import NotFound

from vermouth.resources.project import Project
from vermouth.resources.release import Release
from vermouth.resources.comment import Comment
from vermouth.resources.client import Client
from datetime import datetime

import logging
log = logging.getLogger("vermouth.ticket_handler")

class TicketHandler(DBHandler):
    """
    Override to allow only specific people to edit
    specific things.
    
    For example, people must have privs to add tickets
    to projects.
    """

    def get_projects(self, user):
        if user.has_auth_group("admin"):
            query = Project.find()
        else:
            query = Project.find(members=user.key())
        return query

    def search(self, params, user):
        """
        Overridden to only return projects you are a member of
        unless you are an admin
        """
        objects = []
        query = DBHandler.search(self, params, user)

        if not user.has_auth_group("admin"):
            my_projects = [x for x in self.get_projects(user)]
            if len(my_projects) <= 0:
                raise NotFound()
            query.filter("project =", my_projects)

        return query

    def create(self, obj, user):
        """
        Add the user creating the ticket as the ticket creator
        """
        print "Creating ticket"
        print "Project: %s" % obj.project
        obj.submitted_by = user
        obj.status = "open";
        obj.put()
        # TODO: Add sending message
        return obj

    def update(self, obj, new_obj, user):
        """
        Only employee's can change a ticket
        """
        if not user.has_auth_group("admin"):
            raise Unauthorized()
        # TODO: Add sending a message
        print "Updating ticket"
        print "Project: %s" % obj.project
        return DBHandler.update(self, obj, new_obj, user)

    def delete(self, obj, user):
        """
        Only admins should be able to delete tickets
        """
        if not user.has_auth_group("admin"):
            raise Unauthorized()
        return DBHandler.delete(self, obj, user)
